package com.chenjiahao.kaiyanwan.ui.hot

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chenjiahao.kaiyanwan.R
import com.chenjiahao.kaiyanwan.base.BaseFragment
import com.chenjiahao.kaiyanwan.logic.exception.ExceptionHandle
import com.chenjiahao.kaiyanwan.ui.discovery.CategoryDetailAdapter
import kotlinx.android.synthetic.main.fragment_hot.*
import kotlinx.android.synthetic.main.fragment_rank.*
import kotlinx.android.synthetic.main.fragment_rank.multipleStatusView
import java.lang.Exception

/**
 * Created by chenjh on 2020/9/18
 */
class RankFragment : BaseFragment() {
    override fun getLayoutId() = R.layout.fragment_rank
    private var apiUrl: String? = null

    private val viewModel by lazy { ViewModelProvider(this).get(RankViewModel::class.java) }
    private val mAdapter by lazy {
        activity?.let {
            CategoryDetailAdapter(
                it,
                viewModel.itemList,
                R.layout.item_category_detail
            )
        }
    }

    companion object {
        fun getInstance(apiUrl: String): RankFragment {
            val fragment = RankFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.apiUrl = apiUrl
            return fragment
        }
    }


    override fun initView() {
        mRecyclerView.layoutManager = LinearLayoutManager(activity)
        mRecyclerView.adapter = mAdapter
        mLayoutStatusView = multipleStatusView
        viewModel.rankNextPageUrl = apiUrl

    }

    private fun showLoading() {
        multipleStatusView.showLoading()
    }

    private fun dismissLoading() {
        multipleStatusView.showContent()
    }

    override fun lazyLoad() {
        viewModel.requestRankData()
        showLoading()
        viewModel.getIssueData.observe(this, Observer {
            dismissLoading()
            val RankListData = it.getOrNull()
            if (RankListData != null) {
                viewModel.itemList = RankListData.itemList
                mAdapter?.addData(viewModel.itemList)
            } else {
                showError(
                    ExceptionHandle.handleException(it.exceptionOrNull() as Exception),
                    ExceptionHandle.errorCode
                )
            }
        })
    }
}